package com.example.home;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.example.home.databinding.HomeLeaderboardItemBinding;
import com.example.home.viewmodel.HomeLeaderboardViewModel;

import org.jetbrains.annotations.NotNull;

public class LeaderboardRAdapter extends RecyclerView.Adapter<LeaderboardRAdapter.LeaderboardRHolder> {

    private static final String TAG = "LeaderboardRAdapter";
    private static Integer OVERFLOW = 5;//从第几个绑定后开始加载数据
    private HomeLeaderboardViewModel viewModel;
    public IStartGameDetailActivity iStartGameDetailActivity;//点击跳转接口

    public LeaderboardRAdapter(HomeLeaderboardViewModel homeLeaderboardViewModel) {
        viewModel = homeLeaderboardViewModel;
    }

    @Override
    public LeaderboardRHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        HomeLeaderboardItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()),
                R.layout.home_leaderboard_item, parent, false);

        //创建实例并传递binding
        LeaderboardRHolder holder = new LeaderboardRHolder(binding);
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull LeaderboardRAdapter.LeaderboardRHolder holder, int position) {
        holder.binding.setData(viewModel.getGames().get(position));
        //点击事件
        holder.binding.homeLeaderboardItem.setOnClickListener(v -> iStartGameDetailActivity.openById(holder.binding.getData().getGame().getId()));
        holder.binding.setRank(position+1);
        //判断是否要继续加载排行榜
        if (getItemCount() - position <= OVERFLOW) {
            if (!viewModel.isEnd()) {
                viewModel.getIsGamesLoad().setValue(true);
            }
        }
    }

    @Override
    public int getItemCount() {
        if (viewModel.getGames() == null) {
            return 0;
        } else {
            Log.i(TAG, "getItemCount: "+viewModel.getGames().size());
            return viewModel.getGames().size();
        }
    }

    @Override
    public long getItemId(int position) {
        return super.getItemId(position);
    }

    /*****************************************************************************************************************/
    static class LeaderboardRHolder extends RecyclerView.ViewHolder {
        private HomeLeaderboardItemBinding binding;

        public LeaderboardRHolder(HomeLeaderboardItemBinding homeLeaderboardItemBinding) {
            super(homeLeaderboardItemBinding.getRoot());
            binding = homeLeaderboardItemBinding;
        }
    }
}

